class Slider {
  constructor(id) {
    //id指的是轮播区域标签id
    this.sliderBox = document.getElementById(id);
    this.sliderUl = this.sliderBox.children[0]; //放置轮播区块的ul
    this.sliderList = this.sliderUl.children; //轮播区块
    this.perWidth = this.sliderList[0].offsetWidth; //单个区块的宽度，也是每次ul移动的距离
    this.len = this.sliderList.length; //轮播区块的个数
    this.sliderUl.style.width = this.perWidth * this.len + "px"; //设置轮播区块ul的宽度
    this.i = 0; // 控制展示哪个区块的变量
    this.timer = null; //定时器
    this.clearAndOpen(); //鼠标移到轮播区域上清除定时器，移出开启，这个方法在下面定义，往下找，能找到
    this.autoPlay(); //自动轮播
  }
  move() {
    this.i++; //有个问题，this指向问题

    //123123临界值控制
    if (this.i == this.len) {
      this.sliderUl.style.left = 0;
      this.i = 1;
    }
    //321321临界值控制
    if (this.i == -1) {
      this.sliderUl.style.left = -this.perWidth * (this.len - 1) + "px";
      this.i = this.len - 2;
    }
    //控制小圆点 当前轮播图有小圆点才控制
    if (this.circles) {
      for (let j = 0; j < this.circles.length; j++) {
        this.circles[j].className = "";
      }
      if (this.i == this.len - 1) {
        this.circles[0].className = "hover";
      } else {
        this.circles[this.i].className = "hover";
      }
    }


    startMove(this.sliderUl, {
      left: -this.perWidth * this.i
    });


    // console.log(this.i);
    $('#hdbgi').text(this.i)

  }
  autoPlay() {

    this.timer = setInterval(() => {
      this.move();
    }, 3000);
  }
  addBtn() {
    //添加结构
    let oBtn = document.createElement("div");
    oBtn.className = "btns";
    oBtn.innerHTML = "<span>&lt;</span><span>&gt;</span>";
    this.sliderBox.appendChild(oBtn);
    let lBtn = oBtn.children[0]; //左边的箭头
    let rBtn = oBtn.children[1];
    //添加事件
    lBtn.onclick = () => {
      this.i -= 2;
      this.move();

    }
    rBtn.onclick = () => {
      this.move();
    }
  }
  addCircle() {
    let oUl = document.createElement("ul");
    oUl.className = "circles";
    let str = "";
    for (let j = 0; j < this.len - 1; j++) {
      str += `<li>${j+1}</li>`;
    }
    oUl.innerHTML = str;
    this.sliderBox.appendChild(oUl);

    //小圆点在move方法里使用
    this.circles = oUl.children;
    this.circles[0].className = "hover";

    for (let j = 0; j < this.circles.length; j++) {
      this.circles[j].onmouseover = () => {
        this.i = j - 1;
        this.move();
      }
    }

  }

  //清开定时器
  clearAndOpen() {
    this.sliderBox.onmouseover = () => {
      clearInterval(this.timer);
    }
    this.sliderBox.onmouseout = () => {
      this.timer = setInterval(() => {
        this.move();
      }, 3000);
    }
  }
}